package controllers;

import java.io.File;
import java.util.List;

import models.Author;
import models.Book;
import models.Collection;
import models.Cover;

import org.apache.commons.lang.StringUtils;

import play.Logger;
import play.Play;
import play.cache.Cache;
import play.data.validation.Error;
import play.data.validation.Valid;
import play.data.validation.Validation;
import play.libs.Files;
import play.mvc.Controller;
import utils.AuthorTypeEnum;
import utils.Constants;

public class BookMngt extends Controller {

	protected static final String FROM_ADDING_FORM = "addingbook";
	
    public static void index() {
        render();
    }
    
    public static void displayList() {
    	
    	List<Book> list = Book.findAll();
    	
    	render(list);
    }
    
    
    public static void displayOne(final Long bookId) {
      	
    	Book book = Book.findById(bookId);
    	
    	List<Cover> covers = Cover.find("book = ? order by ordernum", book).fetch(); 
    	
    	render(book, covers);
    }
    
    public static void addForm(final String from) {
    	
    	Cache.set(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDBOOK, from, "30mn");
    	
    	List<Collection> collectionList =  Collection.findAll();
    	List<Author> authorList =  Author.find("byType", AuthorTypeEnum.WRITER.getValue()).fetch();
    	
    	renderArgs.put("from", FROM_ADDING_FORM);
    	render(collectionList, authorList);
    }
    
    
    /**
     * Add the sheet.
     * @throws Throwable 
     */
    public static void add(@Valid final Book book, final File coverFile) throws Throwable {
    	
    	String from = (String) Cache.get(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDBOOK);
    	if (Validation.hasErrors()) {
    		internalPerformError();
    		addForm(from);
    	} 
    	
    	// create book
    	book.create();
    	
    	if (coverFile != null) {
    		String fileName = coverFile.getName();
    		Logger.debug("Il y a une couverture > " + fileName);
    		
    		File to = Play.getFile("public/images/cover/" + fileName);
    		Files.copy(coverFile, to);
    		//OR
    		//coverFile.renameTo(to);
    		//coverFile.delete();
    		
    		// create cover
        	Cover cover = new Cover(book, 1,fileName);
        	cover.create(); 
    	}
    	
    	
    	if (StringUtils.isNotEmpty(from)) {
    		if (ReadingSheetMngt.FROM_ADDING_FORM.equals(from)) {
    			ReadingSheetMngt.addForm();
    			//TODO garder dans le cache ou en session les trucs saisis avant dans la fiche
    		} else {
    			error("Je sais pas où est : " + from);
    		}
    	} else {
    		displayList();
    	}
    }

    

    
    private static void internalPerformError() {
    	
		if (Logger.isDebugEnabled()) {
			Logger.debug("Erreur trouvée dans création book");
			for (Error err : Validation.errors()) {
				Logger.debug(err.message() + " --> pour le champ " + err.getKey());
			}
		}
		
		params.flash(); // add http parameters to the flash scope
		validation.keep(); // keep the errors for the next request
    
    }
}
